package com.snacks;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.snacks.data.Cache;
import com.snacks.data.DataFromHttpSever;
import com.snacks.data.URLconstan;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class Login extends Activity implements OnClickListener {
	private Button btnRegister;
	private Button btnLogin;
	protected static final String Save_Password_Key = "SavePass";

	private EditText User, Pass;
	private CheckBox cbShowPassword, cbSavePass;
	private String prefName = "SavePassWordCheck";
	private SharedPreferences shPref;
	private static final String UserNameKey = "_UserName";
	private static final String PassWordKey = "_PassWord";
	private String prefName1 = "LoginData";
	
	//SVS Test ccc dfsdfds
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		this.cbShowPassword = (CheckBox) findViewById(R.id.ShowThePassWord);
		this.cbSavePass = (CheckBox) findViewById(R.id.Check_SaveUserPass);
		this.User = (EditText) findViewById(R.id.edtUsername);
		this.Pass = (EditText) findViewById(R.id.edtPassword);

		btnRegister = (Button) findViewById(R.id.btnRegist);
		btnLogin = (Button) findViewById(R.id.btnLogin);

		btnRegister.setOnClickListener(this);
		btnLogin.setOnClickListener(this);

		// Số dòng tối đa cho id và pass chỉ là 1
		this.User.setMaxLines(1);
		this.Pass.setMaxLines(1);

		// Load cai dat
		SharedPreferences shPre = getSharedPreferences(prefName, MODE_PRIVATE);
		this.cbSavePass.setChecked(shPre.getBoolean(Save_Password_Key, false));

		// Load Save login info
		this.User.setText(Cache.getCacheUserData());
		this.Pass.setText(Cache.getCacheUserPass());

		cbShowPassword
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (!isChecked) {
							Login.this.Pass
									.setTransformationMethod(PasswordTransformationMethod
											.getInstance());
						} else {
							Login.this.Pass
									.setTransformationMethod(HideReturnsTransformationMethod
											.getInstance());
						}
					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnLogin:

			// Luu lai cai dat khi nguoi dung Check luu thong tin
			shPref = getSharedPreferences(prefName, MODE_PRIVATE);
			SharedPreferences.Editor editor = shPref.edit();
			editor.putBoolean(Save_Password_Key,
					Login.this.cbSavePass.isChecked());
			editor.commit();// save Preferences

			if (!String.valueOf(Login.this.User.getText()).equals("")) {
				CheckLogin(String.valueOf(Login.this.User.getText()),
						String.valueOf(Login.this.Pass.getText()));
			} else {

				AlertDialog.Builder builder = new AlertDialog.Builder(
						Login.this);
				builder.setTitle("Thông báo!");
				builder.setMessage("Bạn phải điền tên đăng nhập\n"
						+ "Nếu chưa có tài khoản bạn vui lòng vào đăng kí"
						+ " để đăng kí tài khoản mới ");
				builder.setNegativeButton("Quay trở về",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				builder.setNeutralButton("Đăng kí",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
								// Chuyển sang form SignUp đăng kí user mới
								startActivity(new Intent()
										.setClass(getApplicationContext(),
												Register.class));
							}
						});

				builder.create().show();
			}

			break;
		case R.id.btnRegist:
			Intent intent1 = new Intent(Login.this, Register.class);
			startActivity(intent1);
		default:
			break;
		}
	}

	// Phương thức kiểm tra tên đăng nhập
	private void CheckLogin(String username, String password) {

		// rq chứa đối tượng reques để gửi lên web service
		ArrayList<NameValuePair> rq = new ArrayList<NameValuePair>();
		rq.add(new BasicNameValuePair("username", username.trim()));
		rq.add(new BasicNameValuePair("password", password.trim()));
		DataFromHttpSever dt = new DataFromHttpSever();
		String result = dt.getDataFromHttpSever(rq, URLconstan.getLoginService());

		// Nếu
		if (result.startsWith("%null&data%")) {
			// Sai ten dang nhap
			OKDialog("Sai mật khẩu...\nVui lòng kiểm tra lại ");
		} else {
			OKDialog("Đăng nhập thành công");
			startActivity(new Intent()
			.setClass(getApplicationContext(),
					Main.class));
		}

	}

	// ==========================================================================
	@Override
	public void onStop() {
		if (cbSavePass.isChecked()) {

			shPref = getSharedPreferences(prefName1, MODE_PRIVATE);
			SharedPreferences.Editor editor = shPref.edit();
			editor.putString(UserNameKey,
					String.valueOf(Login.this.User.getText()).trim());
			editor.putString(PassWordKey,
					String.valueOf(Login.this.Pass.getText()).trim());
			editor.commit();// save Preferences
			Cache.setCacheUserData(String.valueOf(Login.this.User.getText())
					.trim());

		} else {
			shPref = getSharedPreferences(prefName1, MODE_PRIVATE);
			SharedPreferences.Editor editor = shPref.edit();
			editor.putString(UserNameKey, "");
			editor.putString(PassWordKey, "");
			editor.commit();// save Preferences
			Cache.setCacheUserData(String.valueOf(Login.this.User.getText())
					.trim());
		}
		super.onStop();
	}

	// ========================================================================
	@Override
	public void onDestroy() {
		if (cbSavePass.isChecked()) {
			shPref = getSharedPreferences(prefName1, MODE_PRIVATE);
			SharedPreferences.Editor editor = shPref.edit();
			editor.putString(UserNameKey,
					String.valueOf(Login.this.User.getText()).trim());
			editor.putString(PassWordKey,
					String.valueOf(Login.this.Pass.getText()).trim());
			editor.commit();// save Preferences
			Cache.setCacheUserData(String.valueOf(Login.this.User.getText())
					.trim());
		} else {
			shPref = getSharedPreferences(prefName1, MODE_PRIVATE);
			SharedPreferences.Editor editor = shPref.edit();
			editor.putString(UserNameKey, "");
			editor.putString(PassWordKey, "");
			editor.commit();// save Preferences
			Cache.setCacheUserData(String.valueOf(Login.this.User.getText())
					.trim());
		}
		super.onDestroy();
	}

	@SuppressWarnings("javadoc")
	public void OKDialog(String Thongbao) {
		AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
		builder.setTitle("Thông báo!");
		builder.setMessage(Thongbao).setNegativeButton("Quay trở về",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		builder.create().show();
	}

	// =============================================================================
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
		builder.setTitle("Thông báo!");
		builder.setMessage("Bạn có chắc chắn muốn thoát khỏi chương trình?");
		builder.setNegativeButton("Không",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		builder.setCancelable(true);
		builder.setNeutralButton("Có ", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
				finish();
			}
		});
		builder.create().show();
	}
}
